<template>
	<view class="custom-tabs">
	  <view class="custom-tabs-bar" v-for="(item,index) in list" :key="item.id" @click="tabs(item,index)" :class="{active:index===activeIndex}">
	    <text class="tabbar-text">{{item.title}}</text>
	  </view>
	  <view :style="{left:cursor+'px'}" class="custom-tabs-cursor"></view>
	</view>
</template>

<script setup>
	// 自定义tabbar
import {defineProps,ref,getCurrentInstance,onMounted, computed} from "vue"
defineProps({
	list:{
		type:Array,
		default:()=>[]
	}
})
// 获取当前激活的索引
const activeIndex = ref(0)
// 定义一个数组，用于存放每个tabbar的宽度以及距离左侧的距离
const resList=ref([])
// 计算当前激活的tabbar的left值
const cursor= computed(()=>{
	if(resList.value.length===0)return
	const {width,left} =resList.value[activeIndex.value]
	return (width-40)/2+left
})
// 渲染完成后获取每个tabbar的宽度以及距离左侧的距离
 onMounted(()=>{
	 const querySelector= uni.createSelectorQuery().in(getCurrentInstance())
	 querySelector.selectAll(".custom-tabs,.custom-tabs-bar").boundingClientRect(([parent,...res])=>{
	 	 console.log(parent,res);
		resList.value=res.map(({width,left})=>{
			 return {width,left:left-parent.left}
		 })
	 })
	 querySelector.exec()
 })
 //子组件向父组件传递数据
 const tabsEmit=defineEmits(["tabs"])
 // 点击切换tabbar
const tabs=(item,index)=>{
	activeIndex.value=index
	tabsEmit("tabs",item)
}


</script>

<style lang="scss">
// 自定义tabbar
.custom-tabs {
  display: flex;
  position: relative;
  padding: 0 30rpx;
}

.custom-tabs-bar {
  height: 80rpx;
  line-height: 80rpx;
  color: #979797;
  padding-right: 30rpx;
  position: relative;

  &.active {
    color: #121826;
    font-weight: 500;
  }
}

.tabbar-text {
  font-size: 30rpx;
}

.custom-tabs-cursor {
  position: absolute;
  bottom: 3px;
  left: 20px;

  width: 20px;
  height: 2px;
  border-radius: 2px;
  background-color: #2cb5a5;
  transition: all 0.3s ease-out;
}
</style>